package com.wefans.wefansapp.common.tool.network.engine;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.wefans.wefansapp.common.tool.debug.MFDebug;


/**
 * 네트워크 관련된 설정을 얻어올 수 있는 클래스 이다.<br>
 * <b>[사용 권한들]</b><br>
 * &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"&gt;<br>
 * &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"&gt;<br>
 * &lt;uses-permission android:name="android.permission.INTERNET"&gt;<br>
 * 
 * @author kimhyeongbae
 * 
 */
public class MFNetwork
{
    /**
     * Sleep Mode 에서 Wi-Fi가 꺼지지 않도록한 설정한다.
     * 설정후 반드시 setWifiUnlock 호출해주어야 한다.
     * 
     * @param context 컨텍스트
     * @see setWifiUnlock
     */
    private static WifiManager.WifiLock sWifiLock = null;

    /**
     * 단말의 IP 주소를 반환한다.
     * 
     * @param context 컨텍스트
     * @return IP 주소가 담긴 4-size byte array. 실패시 null.
     */
    public static byte[] getIpAddress(Context context)
    {
        MFDebug.d(">> Network::getIpAddress()");
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if(wifiMgr == null || wifiMgr.isWifiEnabled() == false) {
            return null;
        }

        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        if(wifiInfo == null) {
            return null;
        }
        try {
            int nIP = wifiMgr.getConnectionInfo().getIpAddress();
            byte byteIp[] = new byte[4];

            // big endian
            byteIp[0] = (byte) (nIP & 0xff);
            byteIp[1] = (byte) ((nIP >> 8) & 0xff);
            byteIp[2] = (byte) ((nIP >> 16) & 0xff);
            byteIp[3] = (byte) ((nIP >> 24) & 0xff);
            return byteIp;
        } catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 단말의 MAC 주소를 반환한다.
     * 
     * @param context 컨텍스트
     * @return MAC 주소가 담긴 6-size byte array. 실패시 null.
     */
    public static byte[] getMACAddress(Context context)
    {
        MFDebug.d(">> Network::getMACAddress()");
        byte[] byteMacAddr = new byte[6];

        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if(wifiMgr.isWifiEnabled() == false) {
            return null;
        } else {
            String strMac = wifiMgr.getConnectionInfo().getMacAddress();
            strMac = strMac.replace(":", ""); // remove ":"
            strMac = strMac.replace(".", ""); // remove "." ==> SIRIUS

            if(strMac.length() < 12) {
                return null;
            }

            for(int i = 0; i < 6; i++) {
                int nStart = i * 2;
                int nEnd = nStart + 2;
                byteMacAddr[i] = (byte) Integer.parseInt(strMac.substring(nStart, nEnd), 16);
            }
        }
        return byteMacAddr;
    }


    /**
     * 인터넷 사용 가능여부를 확인한다.
     * 
     */
    public static boolean isAvailableInternet()
    {
        MFDebug.d(">> Network::isAvailableInternet()");
        HttpParams httpParam = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParam, 3000);
        HttpConnectionParams.setSoTimeout(httpParam, 3000);

        HttpClient httpClient = new DefaultHttpClient(httpParam);

        URI uri = null;

        try {
            uri = new URI("http://www.google.com");
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }

        HttpGet httpGet = new HttpGet(uri);

        try {
            httpClient.execute(httpGet);
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 3G 연결 허용 여부를 조회한다.
     * 
     * @param context 컨텍스트
     * @return 3G 연결 허용 여부
     */
    public static boolean isNetworkEnabled(Context context)
    {
        MFDebug.d(">> Network::isNetworkEnabled()");
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if(netInfo == null) {
            return false;
        }
        return true;
    }

    /**
     * Wifi 접속 여부를 반환한다.
     * 
     * @param context 컨텍스트
     * @return Wifi 접속 여부
     */
    public static boolean isWifiEnabled(Context context)
    {
        MFDebug.d(">> Network::isWifiEnabled()");
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wifiMgr.getConnectionInfo();

        return (wifiMgr.isWifiEnabled() == true && wInfo.getSSID() != null);
    }

    /**
     * Wifi 모드를 설정한다.
     * 
     * @param context 컨텍스트
     * @param enable 설정 여부
     */
    public static void setWifiEnabled(Context context, boolean bEnable)
    {
        MFDebug.d(">> Network::setWifiEnabled()");
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if(bEnable == false) {
            MFDebug.d("++ bEnable=%d", bEnable);
            if(wifiMgr.isWifiEnabled()) {
                wifiMgr.setWifiEnabled(false);
            }
        } else {
            MFDebug.d("++ bEnable=%d", bEnable);
            wifiMgr.setWifiEnabled(true);
        }
    }

    public static void setWifiLock(Context context)
    {
        MFDebug.d(">> Network::setWifiLock()");
        if(sWifiLock != null) {
            return;
        }

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        sWifiLock = wifiManager.createWifiLock(context.toString());
        sWifiLock.setReferenceCounted(true);
        sWifiLock.acquire();
    }
    
    /**
     * 주어진 url 의 http 서버에 접속하여 서버가 반환하는 바이너리 데이터를 받아온다.
     * 이 메소드는 blocking 으로 동작하며, 사용하는 측에서 thread 를 사용하여 비동기 처리하도록 한다.
     * 
     * @param url http:// 부터 시작하는 서버 url
     * @param requestMsg 서버에 전달하는 request body (없으면 null)
     * @return 서버가 전달하는 body 데이터
     */
    public static byte[] getServerData(String strUrl, String httpMethod, Hashtable<String, String> params)
    {
        MFDebug.d(">> Network::getServerData(String strUrl, String strRequestMsg)");
        byte[] byteData = null;

        HttpURLConnection httpUrlConn = null;
        try {
            URL downUrl = new URL(strUrl);
            httpUrlConn = (HttpURLConnection) downUrl.openConnection();
            httpUrlConn.setConnectTimeout(30 * 1000); // 30 secs
            httpUrlConn.setReadTimeout(30 * 1000); // 30 secs
            httpUrlConn.setUseCaches(false);
            
            //todo 실제 정보 취득가능한 부분은 얻어도록 변경 필요
            httpUrlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpUrlConn.addRequestProperty("SessionKey", "MAMAafklh363KLahkl2");
            httpUrlConn.addRequestProperty("Display", "1024*768");
            httpUrlConn.addRequestProperty("Country", "KOR");
            httpUrlConn.addRequestProperty("DeviceName", "Android_G4");
            httpUrlConn.addRequestProperty("DeviceID", "asdghf45t3");
            httpUrlConn.addRequestProperty("AppVersion", "1.00");
            httpUrlConn.addRequestProperty("OS", "Android");
            httpUrlConn.addRequestProperty("OSVer", "4.4.2");

            // send request body
            if(params != null) {
                httpUrlConn.setDoOutput(true);
                httpUrlConn.connect();
                
                StringBuffer sb = new StringBuffer();
                
                Enumeration<String> enumeration = params.keys();
                while(enumeration.hasMoreElements()) {
                    String key = enumeration.nextElement().toString();
                    String value = params.get(key);
                    
                    sb.append(key).append("=").append(value).append("&");
                }

                OutputStream outStream = httpUrlConn.getOutputStream();
                outStream.write(sb.toString().getBytes());
                outStream.flush();
                outStream.close();
            } else {
                httpUrlConn.connect();
            }

            int nResCode = httpUrlConn.getResponseCode();
            if(nResCode != HttpURLConnection.HTTP_OK) {
                String strResMsg = httpUrlConn.getResponseMessage();
                MFDebug.w("Http Response error:%d (%s)", nResCode, strResMsg);
                return null;
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream();
            byte[] byteBuf = new byte[10 * 1024];

            int nSize = httpUrlConn.getContentLength();
            if(nSize < 0) {
                MFDebug.w("Content-length is invalid");

                int nLen = 0;

                while(true) {
                    nLen = inputStream.read(byteBuf);
                    if(nLen < 0) {
                        break;
                    }
                    byteArrayOutStream.write(byteBuf, 0, nLen);
                }
                byteArrayOutStream.flush();
            } else {
                int nLen = 0, nRead = 0, nTotal = nSize;

                while(nRead < nTotal) {
                    nLen = inputStream.read(byteBuf);
                    nRead += nLen;
                    byteArrayOutStream.write(byteBuf, 0, nLen);
                }
                byteArrayOutStream.flush();
            }

            byteData = byteArrayOutStream.toByteArray();
            byteArrayOutStream.close();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(httpUrlConn != null) {
                httpUrlConn.disconnect();
            }
        }

        return byteData;
    }


//    /**
//     * 주어진 url 의 http 서버에 접속하여 서버가 반환하는 바이너리 데이터를 받아온다.
//     * 이 메소드는 blocking 으로 동작하며, 사용하는 측에서 thread 를 사용하여 비동기 처리하도록 한다.
//     * 
//     * @param url http:// 부터 시작하는 서버 url
//     * @param requestMsg 서버에 전달하는 request body (없으면 null)
//     * @return 서버가 전달하는 body 데이터
//     */
//    public static byte[] getServerData(String strUrl, String httpMethod, String strRequestMsg)
//    {
//        MFDebug.d(">> Network::getServerData(String strUrl, String strRequestMsg)");
//        byte[] byteData = null;
//
//        HttpURLConnection httpUrlConn = null;
//        try {
//            URL downUrl = new URL(strUrl);
//            httpUrlConn = (HttpURLConnection) downUrl.openConnection();
//            httpUrlConn.setConnectTimeout(30 * 1000); // 30 secs
//            httpUrlConn.setReadTimeout(30 * 1000); // 30 secs
//            httpUrlConn.setUseCaches(false);
//            
//            //todo 실제 정보 취득가능한 부분은 얻어도록 변경 필요
//            httpUrlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            httpUrlConn.addRequestProperty("SessionKey", "MAMAafklh363KLahkl2");
//            httpUrlConn.addRequestProperty("Display", "1024*768");
//            httpUrlConn.addRequestProperty("Country", "KOR");
//            httpUrlConn.addRequestProperty("DeviceName", "Android_G4");
//            httpUrlConn.addRequestProperty("DeviceID", "asdghf45t3");
//            httpUrlConn.addRequestProperty("AppVersion", "1.00");
//            httpUrlConn.addRequestProperty("OS", "Android");
//            httpUrlConn.addRequestProperty("OSVer", "4.4.2");
//
//            // send request body
//            if(strRequestMsg != null) {
//                httpUrlConn.setDoOutput(true);
//                httpUrlConn.connect();
//
//                OutputStream outStream = httpUrlConn.getOutputStream();
//                outStream.write(strRequestMsg.getBytes());
//                outStream.flush();
//                outStream.close();
//            } else {
//                httpUrlConn.connect();
//            }
//
//            int nResCode = httpUrlConn.getResponseCode();
//            if(nResCode != HttpURLConnection.HTTP_OK) {
//                String strResMsg = httpUrlConn.getResponseMessage();
//                MFDebug.w("Http Response error:%d (%s)", nResCode, strResMsg);
//                return null;
//            }
//
//            InputStream inputStream = httpUrlConn.getInputStream();
//            ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream();
//            byte[] byteBuf = new byte[10 * 1024];
//
//            int nSize = httpUrlConn.getContentLength();
//            if(nSize < 0) {
//                MFDebug.w("Content-length is invalid");
//
//                int nLen = 0;
//
//                while(true) {
//                    nLen = inputStream.read(byteBuf);
//                    if(nLen < 0) {
//                        break;
//                    }
//                    byteArrayOutStream.write(byteBuf, 0, nLen);
//                }
//                byteArrayOutStream.flush();
//            } else {
//                int nLen = 0, nRead = 0, nTotal = nSize;
//
//                while(nRead < nTotal) {
//                    nLen = inputStream.read(byteBuf);
//                    nRead += nLen;
//                    byteArrayOutStream.write(byteBuf, 0, nLen);
//                }
//                byteArrayOutStream.flush();
//            }
//
//            byteData = byteArrayOutStream.toByteArray();
//            byteArrayOutStream.close();
//        } catch(Exception e) {
//            e.printStackTrace();
//        } finally {
//            if(httpUrlConn != null) {
//                httpUrlConn.disconnect();
//            }
//        }
//
//        return byteData;
//    }
 
    /**
     * 주어진 url 의 http 서버에 접속하여 서버가 반환하는 바이너리 데이터를 받아온다.
     * 이 메소드는 blocking 으로 동작하며, 사용하는 측에서 thread 를 사용하여 비동기 처리하도록 한다.
     * strUrl이 https://로 시작하면 httpsURLConnection을 사용한다.
     * 
     * @param url http:// 부터 시작하는 서버 url
     * @param requestMsg 서버에 전달하는 request body (없으면 null) nTimeout Second
     * @return 서버가 전달하는 body 데이터
     * @author 오정채
     */
    public static byte[] getServerData(String strUrl, String strRequestMsg, int nTimeout, boolean bTrustAll)
    {
        MFDebug.d(">> Network::getServerData(String strUrl, String strRequestMsg)");
        byte[] byteData = null;

        
        boolean bHttps = false;
        int nSize = 0;
        byte[] byteBuf = new byte[10 * 1024];
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutStream = null;
        try {
            URL downUrl = new URL(strUrl);
            if(strUrl.toLowerCase().indexOf("https://")==0 && bTrustAll == false)
            {
                HttpsURLConnection httpsUrlConn = null;
                httpsUrlConn = (HttpsURLConnection) downUrl.openConnection();
                httpsUrlConn.setConnectTimeout(nTimeout * 1000); 
                httpsUrlConn.setReadTimeout(nTimeout * 1000);
                httpsUrlConn.setUseCaches(false);
                
                // send request body
                if(strRequestMsg != null) {
                    httpsUrlConn.setDoOutput(true);
                    httpsUrlConn.connect();
    
                    OutputStream outStream = httpsUrlConn.getOutputStream();
                    outStream.write(strRequestMsg.getBytes());
                    outStream.flush();
                    outStream.close();
                } else {
                    httpsUrlConn.connect();
                }
    
                int nResCode = httpsUrlConn.getResponseCode();
                if(nResCode != HttpURLConnection.HTTP_OK) {
                    String strResMsg = httpsUrlConn.getResponseMessage();
                    MFDebug.w("Http Response error:%d (%s)", nResCode, strResMsg);
                    return null;
                }
                inputStream = httpsUrlConn.getInputStream();
                byteArrayOutStream = new ByteArrayOutputStream();
                nSize = httpsUrlConn.getContentLength();
                
                if(nSize < 0) {
                    MFDebug.w("Content-length is invalid");

                    int nLen = 0;

                    while(true) {
                        nLen = inputStream.read(byteBuf);
                        if(nLen < 0) {
                            break;
                        }
                        byteArrayOutStream.write(byteBuf, 0, nLen);
                    }
                    byteArrayOutStream.flush();
                } else {
                    MFDebug.w("nSize = "+nSize);
                    int nLen = 0, nRead = 0, nTotal = nSize;

                    while(nRead < nTotal) {
                        nLen = inputStream.read(byteBuf);
                        nRead += nLen;
                        byteArrayOutStream.write(byteBuf, 0, nLen);
                    }
                    byteArrayOutStream.flush();
                }

                byteData = byteArrayOutStream.toByteArray();
                byteArrayOutStream.close();
                
                if(httpsUrlConn != null) {
                    httpsUrlConn.disconnect();
                }
            } else
            {
                HttpURLConnection httpUrlConn = null;
                httpUrlConn = (HttpURLConnection) downUrl.openConnection();
                
                if(strUrl.toLowerCase().indexOf("https://")==0 && bTrustAll == true)
                {
                    ((HttpsURLConnection) httpUrlConn).setHostnameVerifier( DO_NOT_VERIFY );
                }
                
                httpUrlConn.setConnectTimeout(nTimeout * 1000); // 30 secs
                httpUrlConn.setReadTimeout(nTimeout * 1000); // 30 secs
                httpUrlConn.setUseCaches(false);
                httpUrlConn.setRequestProperty("Accept-Encoding", "Gzip");
                
                
                // send request body
                if(strRequestMsg != null) {//POST
                    httpUrlConn.setDoOutput(true);
                    httpUrlConn.connect();
    
                    OutputStream outStream = httpUrlConn.getOutputStream();
                    outStream.write(strRequestMsg.getBytes());
                    outStream.flush();
                    outStream.close();
                } else {//GET
                    httpUrlConn.connect();
                }
    
                int nResCode = httpUrlConn.getResponseCode();
                if(nResCode != HttpURLConnection.HTTP_OK) {
                    String strResMsg = httpUrlConn.getResponseMessage();
                    MFDebug.w("Http Response error:%d (%s)", nResCode, strResMsg);
                    return null;
                }
    
                inputStream = httpUrlConn.getInputStream();
                byteArrayOutStream = new ByteArrayOutputStream();
                nSize = httpUrlConn.getContentLength();
                
                
                if(nSize < 0) {
                    MFDebug.w("Content-length is invalid");

                    int nLen = 0;

                    while(true) {
                        nLen = inputStream.read(byteBuf);
                        if(nLen < 0) {
                            break;
                        }
                        byteArrayOutStream.write(byteBuf, 0, nLen);
                    }
                    byteArrayOutStream.flush();
                } else {
                    MFDebug.w("nSize = "+nSize);
                    int nLen = 0, nRead = 0, nTotal = nSize;

                    while(nRead < nTotal) {
                        nLen = inputStream.read(byteBuf);
                        nRead += nLen;
                        byteArrayOutStream.write(byteBuf, 0, nLen);
                    }
                    byteArrayOutStream.flush();
                }

                byteData = byteArrayOutStream.toByteArray();
                byteArrayOutStream.close();
                
                if(httpUrlConn != null) {
                    httpUrlConn.disconnect();
                }
            }
            
            
        } catch(Exception e) {
            e.printStackTrace();
        }

        return byteData;
    }
    
    public static byte[] uploadFile(String strUrl, String filepath, String filename) {

    	String result=null;
	    HttpURLConnection conn = null;
	    DataOutputStream dos = null;
	    DataInputStream inStream = null;
	    String existingFileName =null;
	    String lineEnd = "\r\n";
	    String twoHyphens = "--";
	    String boundary = "*****";
	    int bytesRead, bytesAvailable, bufferSize;
	    byte[] buffer;
	    int maxBufferSize = 1 * 1024 * 1024;
	    String responseFromServer = "";
//	    String url_string=
	    String urlString = strUrl;
	    existingFileName= filepath;
	    try {
	    	
	        //------------------ CLIENT REQUEST
	        FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
	        // open a URL connection to the Servlet
	        URL url = new URL(urlString);
	        // Open a HTTP connection to the URL
	        conn = (HttpURLConnection) url.openConnection();
	        // Allow Inputs
	        conn.setDoInput(true);
	        // Allow Outputs
	        conn.setDoOutput(true);
	        // Don't use a cached copy.
	        conn.setUseCaches(false);
	        // Use a post method.
	        conn.setRequestMethod("POST");
	        conn.setRequestProperty("Connection", "Keep-Alive");
	        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	        
	        conn.setRequestProperty("SessionKey", "MAMAafklh363KLahkl2");
	        conn.setRequestProperty("Display", "1024*768");
	        conn.setRequestProperty("Country", "KOR");
	        conn.setRequestProperty("DeviceName", "Android_G4");
	        conn.setRequestProperty("DeviceID", "asdghf45t3");
	        conn.setRequestProperty("AppVersion", "1.00");
	        conn.setRequestProperty("OS", "Android");
	        conn.setRequestProperty("OSVer", "4.4.2");
            
	        dos = new DataOutputStream(conn.getOutputStream());
	        dos.writeBytes(twoHyphens + boundary + lineEnd);
	        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
	        dos.writeBytes(lineEnd);
	        // create a buffer of maximum size
	        bytesAvailable = fileInputStream.available();
	        bufferSize = Math.min(bytesAvailable, maxBufferSize);
	        buffer = new byte[bufferSize];
	        // read file and write it into form...
	        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

	        while (bytesRead > 0) {

	            dos.write(buffer, 0, bufferSize);
	            bytesAvailable = fileInputStream.available();
	            bufferSize = Math.min(bytesAvailable, maxBufferSize);
	            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

	        }

	        // send multipart form data necesssary after file data...
	        dos.writeBytes(lineEnd);
	        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	        // close streams
//	        Log.e("Debug", "File is written");
	        MFDebug.e("File is written");
	        fileInputStream.close();
	        dos.flush();
	        dos.close();

	    } catch (MalformedURLException ex) {
//	        Log.e("Debug", "error: " + ex.getMessage(), ex);
	    	MFDebug.e("error");
	    } catch (IOException ioe) {
	    	MFDebug.e("error");
	    }

	    //------------------ read the SERVER RESPONSE
	    try {

	        inStream = new DataInputStream(conn.getInputStream());
	        InputStreamReader reader = new InputStreamReader(inStream, "UTF-8");
	        String str;
	        
			StringBuffer sb = new StringBuffer();
			String strData = null;
			char[] buff;        

			while (true) {
				buff = new char[1024 * 16];
				if (reader.read(buff) == -1)
					break;
				strData = new String(buff);
				sb.append(strData.trim());
			}
			
			if (reader != null)
				reader.close();
			if(inStream!=null)
				inStream.close();
			
			result = sb.toString();
			
	        inStream.close();

	    } catch (IOException ioex) {
	    	MFDebug.e("File is written");
	    	return null;
	    }
		return result.getBytes();
	}

    /**
     * Sleep Mode 에서 Wi-Fi가 꺼지지 않도록한 설정을 해제한다.<br>
     * setWifiLock 로 설정한 후에야 적용된다.
     * 
     * @see setWifiLock
     */
    public void setWifiUnlock()
    {
        MFDebug.d(">> Network::setWifiUnlock()");
        if(sWifiLock == null) {
            return;
        }

        sWifiLock.release();
        sWifiLock = null;
    }
    
    private static void trustAllHosts() { 
        // Create a trust manager that does not validate certificate chains 
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { 
                public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
                        return new java.security.cert.X509Certificate[] {}; 
                } 
 
                @Override 
                public void checkClientTrusted( 
                        java.security.cert.X509Certificate[] chain, 
                        String authType) 
                        throws java.security.cert.CertificateException { 
                    // TODO Auto-generated method stub 
                     
                } 
 
                @Override 
                public void checkServerTrusted( 
                        java.security.cert.X509Certificate[] chain, 
                        String authType) 
                        throws java.security.cert.CertificateException { 
                    // TODO Auto-generated method stub 
                     
                } 
        } }; 
 
        // Install the all-trusting trust manager 
        try { 
                SSLContext sc = SSLContext.getInstance("TLS"); 
                sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
                HttpsURLConnection 
                                .setDefaultSSLSocketFactory(sc.getSocketFactory()); 
        } catch (Exception e) { 
                e.printStackTrace(); 
        } 
    } 
     
    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        } 
    };
    
    public static InputStream getInputStreamFromUrl(String url) {
		InputStream contentStream = null;

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(url));
			contentStream = response.getEntity().getContent();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return contentStream;
	}

    public static String getStringFromUrl(String url) {
		BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));

		StringBuffer sb = new StringBuffer();

		try {
			String line = null;

			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
